/**
 * 销售业绩
 */
define(function (require) {
    'use strict';
    var $ = require('jquery');
    var angular = require('angular');
    require('angular-route');
    var util = require('util');
    var _ = require('underscore');
    require('angular-ui');
    require('angular-interceptor');
    require('/ydxs_static/public/js/plugins/filterCombobox');
    require('./project_service');
    require('./team_service');
    require('/ydxs_static/public/js/service/init_settings/equationService');
    require('/static_public/node_modules/jquery-treetable/jquery.treetable.cmd');
    require('./upload_service');
    
    require('/static_public/js/angular_directive/projectTreeSelector');

    angular.module('performanceReportApp', ['ngRoute', 'ngInterceptor', 'ngUI','filterCombobox','equationServiceApp','teamServiceApp', 'projectServiceApp', 'uploadServiceApp','projectTreeSelector'])
        .config(['$routeProvider', function ($routeProvider) {
            $routeProvider
                .when('/total', {templateUrl: 'inc/performance_total.html', controller: 'performanceTotalCtl'})
                .when('/detail', {templateUrl: 'inc/performance_detail.html', controller: 'performanceDetailCtl'})
                .otherwise({redirectTo: '/total'});
        }])
        .factory('performanceReportService', ['$http', function ($http) {
            function httpGet(url, data) {
                url = '/api/index.php?r=' + url;
                return $http.get(url, {params: data});
            }

            return {
                getQueryParams : function(scope){
                    return {
                        proj_id : scope.curProjectId,
                        date_mode : scope.dateMode,
                        team_id: scope.query.teamId?scope.query.teamId:scope.teamId,
                        group_id: scope.query.groupId?scope.query.groupId:scope.groupId,
                        user_id : scope.query.salerId,
                        row_type: scope.rowType,
                        user_type : scope.userType,
                        index : scope.query.pageIndex-1,
                        page_index : scope.query.pageIndex,
                        page_size : scope.query.pageSize,
                        totalType : scope.totalType
                    };
                },
                getList: function (scope) {
                    var url;
                    url = 'ydxs/sale-report/list';
                    var data = this.getQueryParams(scope);
                    if(scope.totalType === 'hk'){
                        data.type = 'hk';
                    }
                    httpGet(url, data)
                        .then(function (res) {
                            //列表
                            scope.performanceReportList = res.data.data.info || [];
                            scope.query.total = res.data.data.sum;
                        }).finally(function () {
                            scope.loading = false;
                        });
                },
                getTeamList: function (curProjectId) {
                    var url = 'ydxs/sale-report/get-achievement';
                    var data = {
                        proj_id: curProjectId
                    };
                    return httpGet(url, data).then(function (res) {
                        return res.data.data || [];
                    });
                }
            };
        }])
        .controller('performanceReportCtrl', ['$scope','$rootScope', '$timeout', 'projectService', 'uploadService', 'performanceReportService', function ($scope,$rootScope, $timeout, projectService) {
            /* 局部变量 start */

            /* 局部变量 end */

            /* $scope变量 start */


            /* $scope变量 end */

            /* $scope变量 watch start */
            $scope.$watch('curProjectId', function () {
                if ($scope.curProjectId) {
                    $rootScope.curProjectId = $scope.curProjectId;
                    $scope.$broadcast('changeCurProjectId', $scope.curProjectId);

                    //$scope.getList();
                }
            });
            /* $scope变量 watch end */


            /* $scope方法 start */

            /* $scope方法 end */

            //init
            projectService.getProjectList().then(function (data) {
                $scope.projectList = data.projectList;
                $rootScope.curProjectId = $scope.curProjectId = data.projectId;
            });
        }])
        .controller('performanceTotalCtl', ['$scope','$rootScope','$routeParams','equationService','performanceReportService','uploadService',
            function ($scope,$rootScope,$routeParams,equationService,performanceReportService,uploadService) {
            /* 局部变量 start */
            function sortTeamTree(teamArr){
                if(!teamArr) {return;}
                function Node(obj,level,data){
                    this.obj = obj;
                    this.level = level || 0;
                    this.children  = [];
                    //console.info(this.level);
                    this.setChildren(this,data);
                }
                Node.prototype.setChildren=function(node,data){
                    var obj = node.obj;
                    if(obj.team_id===''){return;}
                    var tempChildren = data[obj.team_id];
                    if(tempChildren){
                        _.each(tempChildren,function(child){
                            var childNode = new Node(child,node.level+1,data);
                            node.children.push(childNode);
                        });
                    }
                };
                function treeToArr(node,ret){
                    ret.push(node.obj);
                    var sortArr = _.sortBy(node.children,function(item){return item.obj.sort_order;});
                    _.each(sortArr,function(child){
                        treeToArr(child,ret);
                    });
                }
                var groupObj = _.groupBy(teamArr,'parent_id');

                var ret = [];
                //项目的parentid为'-1'
                var projectArr = groupObj['-1'];
                if(projectArr && projectArr.length > 0){
                    var root = new Node(projectArr[0],0,groupObj);
                    treeToArr(root,ret);
                }else{
                    util.alert('找不到项目,请联系系统管理员');
                }
                return ret;
            }

            function initTotal(curProjectId){
                //equationService.getEquation().then(function(data){
                //    $scope.equation = data;
                //});
                performanceReportService.getTeamList(curProjectId).then(function (teamObj) {
                    $scope.teamObj = teamObj;
                    $scope.teamRmb = sortTeamTree(teamObj.rmb);
                    $scope.teamTs = sortTeamTree(teamObj.ts);
                    $scope.teamArea = sortTeamTree(teamObj.area);
                    $scope.teamHk = sortTeamTree(teamObj.hk);
                    $scope.$applyAsync(function () {
                        //第二个参数为true，强制重新渲染树
                        $('.performance_table').treetable({expandable: true,initialState:'expanded'},true);
                        $scope.loading = false;
                    });
                });
            }
            /* 局部变量 end */

            /* $scope变量 start */
            $scope.loading = true;

            /* $scope变量 end */

            /* $scope变量 watch start */
            $scope.$on('changeCurProjectId', function (event, curProjectId) {
                initTotal(curProjectId);
            });
            /* $scope变量 watch end */


            /* $scope方法 start */
            $scope.beforeUpload = function ($dialog, $dialogScope) {
                $dialogScope.proj_id = $rootScope.curProjectId;
                uploadService.beforeUpload($dialog, $dialogScope,$scope);
            };
            $scope.downloadTemplate = function () {
                location.href = '/api/index.php?r=ydxs/sale-report/export-template&proj_id='+$rootScope.curProjectId+'&token='+util.getToken();
            };
            /* $scope方法 end */

            //init
            $rootScope.curProjectId && initTotal($rootScope.curProjectId);

        }])
        .controller('performanceDetailCtl', ['$scope','$rootScope','$routeParams','teamService','performanceReportService',
            function ($scope,$rootScope,$routeParams,teamService,performanceReportService) {
            /* 局部变量 start */
            function initDetail(curProjectId){
                $scope.curProjectId = curProjectId;
                $scope.dateMode = $routeParams.dateMode;
                $scope.type = $routeParams.type;
                $scope.rowType = $routeParams.rowType;
                $scope.userType = $routeParams.userType;
                $scope.totalType = $routeParams.totalType;
                if($scope.rowType==='team_id'){
                    $scope.teamId = $routeParams.teamId;
                }else if($scope.rowType==='group_id'){
                    $scope.groupId = $routeParams.teamId;
                }else if($scope.rowType==='other'){

                }
                $scope.getList();
                teamService.getTeamList($scope);
            }
            var initQuery = {
                pageIndex : 1,
                pageSize : 10,
                total : 0,
                groupDisabled : true,
                salerDisabled : true,
                teamId : '',
                groupId : '',
                salerId : ''
            };
            /* 局部变量 end */

            /* $scope变量 start */
            $scope.query = angular.copy(initQuery);


            /* $scope变量 end */

            /* $scope变量 watch start */
            $scope.$on('changeCurProjectId', function (event, curProjectId) {
                initDetail(curProjectId);
            });
                $scope.$watch('query.teamId', function (newValue, oldValue) {
                    if(newValue && newValue !== oldValue){
                        var groups = _.find($scope.teamDatas,function(item){ return item.team_id === newValue; }).groups;
                        $scope.groupList = _.map(groups, function (item) {
                            item.text = item.group_name;
                            return item;
                        });
                        $scope.query.groupDisabled = false;
                    }
                });
                $scope.$watch('query.groupId', function (newValue, oldValue) {
                    if(newValue && newValue !== oldValue){
                        var groups = _.find($scope.teamDatas,function(item){ return item.team_id === $scope.query.teamId; }).groups;
                        var salers = _.find(groups,function(item){ return item.group_id === newValue; }).salers;
                        $scope.salerList = _.map(salers, function (item) {
                            item.text = item.user_name;
                            return item;
                        });
                        $scope.query.salerDisabled = false;
                    }
                });
            /* $scope变量 watch end */


            /* $scope方法 start */
            $scope.resetQuery = function () {
                $scope.query = angular.copy(initQuery);
            };
            $scope.getList = function(pageIndex){
                pageIndex || (pageIndex = 1);
                $scope.query.pageIndex = pageIndex;
                performanceReportService.getList($scope);
            };
            $scope.exportData = function () {
                var data = performanceReportService.getQueryParams($scope);
                data.totalType = $scope.totalType;
                location.href = '/api/index.php?r=ydxs/sale-report/list&is_export=1&'+ $.param(data);
            };
            $scope.filterDate = function (str) {
                return str?str.substr(0,10):'';
            };
            /* $scope方法 end */

            //init
            $rootScope.curProjectId && initDetail($rootScope.curProjectId);
        }]);
    angular.element(document).ready(function () {
        angular.bootstrap(document, ['performanceReportApp']);
    });
});
